
/**
 * @param map  Object
 * @returns { label, value } 对象转变成[{label, value }]形式
 */
export const mapToOptions = (map: Record<string, string | number | boolean> = {}) =>
  Object.entries(map).map(([value, label]) => ({ label, value }));

/**
 *
 * @param js 要转换的值
 * @param type 1: stringify, 2: parse
 * @returns
 */
export const formatJson = (js: string | any, type = 1) => {
  try {
    return type === 1 ? JSON.stringify(js) : JSON.parse(js);
  }catch(error) {
    // console.error('error: ', error);
    return undefined;
  }
};
export interface newTree  {
  name?: string,
  children?: newTree[]
}

/**
 * 将权限路由string[][]转化为 tree形式方便进行路由匹配
 * @param auth string[][] 的参数格式
 */
export const authRouterToTree = (auth: string[][], idx:number = 0, fatherKey?:string) => {
  return auth?.reduce((pre: newTree[], cur) => {
    const obj:newTree = {};
    const key =  pre?.find((item: any) => item?.name == cur[idx]);
    if(!key && fatherKey === cur[idx - 1]){
      if(idx == cur?.length - 1){
        pre.push(cur[idx] as newTree);
      }else{
        obj.name = cur[idx];
        if(idx < cur?.length - 1){
          obj.children = authRouterToTree(auth, idx + 1, obj.name);
        }
        pre.push(obj);
      }
    }
    return pre;
  }, []);
};
